<template>
  <div>
    <a-form layout="inline" :model="searchForm">
      <a-form-item label="客户名称">
        <a-input v-model:value="searchForm.customerName"></a-input>
      </a-form-item>
      <a-form-item label="客户订单号">
        <a-input v-model:value="searchForm.customerOrder"></a-input>
      </a-form-item>
      <a-form-item label="产品名称">
        <a-input v-model:value="searchForm.productName"></a-input>
      </a-form-item>
      <a-form-item label="产品型号">
        <a-input v-model:value="searchForm.productModel"></a-input>
      </a-form-item>
      <a-form-item label="物料代码">
        <a-input v-model:value="searchForm.materialCode"></a-input>
      </a-form-item>
      <a-form-item label="下单日期">
        <a-date-picker v-model:value="searchForm.beginOrderDate" placeholder="开始日期" format="YYYY-MM-DD"></a-date-picker>
        <a-date-picker v-model:value="searchForm.endOrderDate" placeholder="结束日期" format="YYYY-MM-DD"></a-date-picker>
      </a-form-item>
      <a-form-item label="合同交期">
        <a-date-picker v-model:value="searchForm.beginDeliveryDate" placeholder="开始日期"
          format="YYYY-MM-DD"></a-date-picker>
        <a-date-picker v-model:value="searchForm.endDeliveryDate" placeholder="结束日期"
          format="YYYY-MM-DD"></a-date-picker>
      </a-form-item>
      <a-form-item label="变更后交期">
        <a-date-picker v-model:value="searchForm.beginChangeDate" placeholder="开始日期"
          format="YYYY-MM-DD"></a-date-picker>
        <a-date-picker v-model:value="searchForm.endChangeDate" placeholder="结束日期" format="YYYY-MM-DD"></a-date-picker>
      </a-form-item>
    </a-form>
    <div class="btmOption" style="display: flex; justify-content: space-between; margin-top: 16px">
      <!-- 左侧按钮组 -->
      <div>
        <a-button type="primary" @click="handleAdd" style="margin-right: 8px">
          <template #icon>
            <PlusOutlined />
          </template>
          新增
        </a-button>
        <a-button type="link" @click="handleImport" style="margin-right: 8px">
          <template #icon>
            <UploadOutlined />
          </template>
          导入
        </a-button>
        <a-button type="link" @click="handleExport">
          <template #icon>
            <DownloadOutlined />
          </template>
          导出
        </a-button>
      </div>

      <!-- 右侧按钮组 -->
      <div>
        <a-button type="primary" @click="handleSearch" :loading="loadingSearch" style="margin-right: 8px">
          <template #icon>
            <SearchOutlined />
          </template>
          搜索
        </a-button>
        <a-button @click="handleReset">
          <template #icon>
            <SyncOutlined />
          </template>
          重置
        </a-button>
      </div>
    </div>
    <a-table sticky :columns="columns" :data-source="tableData" :scroll="{ x: 1500, y: 600 }" :pagination="false">
      <template #bodyCell="{ column }">
        <template v-if="column.key === 'option'">
          <div class="option-class"><a>编辑</a><a>查看</a><a>删除</a></div>
        </template>
      </template>
      <template #footer>
        123123
      </template>

    </a-table>

    <FormComponent ref="formComponent" @refresh="handleSearch" />
    <DetailComponent ref="detailComponent" />
    <ImportComponent ref="importComponent" @refresh="handleSearch" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import type { TableColumnsType } from 'ant-design-vue';
import FormComponent from './form.vue';
import ImportComponent from './import.vue';
import DetailComponent from './detail.vue';
import { getList, deleteBydSpecialPojectDataById } from './helper/api';

const columns = ref<TableColumnsType>([
  { title: '部门', width: 150, dataIndex: 'department', key: 'department' },
  { title: '业务员', width: 150, dataIndex: 'salesman', key: 'salesman' },
  { title: '客户名称', width: 200, dataIndex: 'customerName', key: 'customerName' },
  { title: '客户订单号', width: 150, dataIndex: 'customerOrder', key: 'customerOrder' },
  { title: '类别', width: 100, dataIndex: 'category', key: 'category' },
  { title: '物料代码', width: 100, dataIndex: 'materialCode', key: 'materialCode' },
  { title: '产品名称', width: 100, dataIndex: 'productName', key: 'productName' },
  { title: '产品型号', width: 100, dataIndex: 'productModel', key: 'productModel' },
  { title: '合同备注', width: 100, dataIndex: 'contractRemarks', key: 'contractRemarks' },
  { title: '单位', width: 100, dataIndex: 'unit', key: 'unit' },
  { title: '订单数量', width: 100, dataIndex: 'orderQuantity', key: 'orderQuantity' },
  { title: '下单日期', width: 150, dataIndex: 'orderDate', key: 'orderDate' },
  { title: '合同交期', width: 150, dataIndex: 'deliveryDate', key: 'deliveryDate' },
  { title: '变更后交期', width: 150, dataIndex: 'changeDate', key: 'changeDate' },
  { title: '责任工程师', width: 120, dataIndex: 'responsibleEngineer', key: 'responsibleEngineer' },
  { title: '在制状态', width: 100, dataIndex: 'productionStatus', key: 'productionStatus' },
  { title: '入库时间', width: 150, dataIndex: 'storageTime', key: 'storageTime' },
  { title: '出货日期', width: 150, dataIndex: 'shippingDate', key: 'shippingDate' },
  { title: '是否外协', width: 100, dataIndex: 'outsourced', key: 'outsourced' },
  { title: '投产数量', width: 100, dataIndex: 'productionQuantity', key: 'productionQuantity' },
  { title: '已发货数量', width: 120, dataIndex: 'quantityShipped', key: 'quantityShipped' },
  { title: '备注', width: 100, dataIndex: 'remarks', key: 'remarks' },
  {
    title: '操作',
    key: 'option',
    fixed: 'right',
    width: 150,
  },
]);

// 定义接口类型
interface SearchForm {
  customerName: string;
  customerOrder: string;
  productName: string;
  productModel: string;
  materialCode: string;
  beginOrderDate: string | null;
  endOrderDate: string | null;
  beginDeliveryDate: string | null;
  endDeliveryDate: string | null;
  beginChangeDate: string | null;
  endChangeDate: string | null;
}

interface TableRow {
  id: number | string;
  department: string;
  salesman: string;
  customerName: string;
  customerOrder: string;
  category: string;
  materialCode: string;
  productName: string;
  productModel: string;
  contractRemarks: string;
  unit: string;
  orderQuantity: string;
  orderDate: string;
  deliveryDate: string;
  changeDate: string;
  responsibleEngineer: string;
  productionStatus: string;
  storageTime: string;
  shippingDate: string;
  outsourced: string;
  productionQuantity: string;
  quantityShipped: string;
  remarks: string;
}

// 响应式数据
const searchForm = reactive<SearchForm>({
  customerName: '',
  customerOrder: '',
  productName: '',
  productModel: '',
  materialCode: '',
  beginOrderDate: null,
  endOrderDate: null,
  beginDeliveryDate: null,
  endDeliveryDate: null,
  beginChangeDate: null,
  endChangeDate: null
});

const tableData = ref<TableRow[]>([]);
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loadingSearch = ref(false);
const loadingTable = ref(false);
// 修改删除状态为对象类型，按行ID存储
const deleteVisible = ref<Record<string | number, boolean>>({});

// 组件引用
const formComponent = ref<InstanceType<typeof FormComponent>>();
const detailComponent = ref<InstanceType<typeof DetailComponent>>();
const importComponent = ref<InstanceType<typeof ImportComponent>>();

// 方法定义
const handleSearch = async () => {
  loadingSearch.value = true;
  loadingTable.value = true;
  try {
    const res = await getList(searchForm, pageNum.value, pageSize.value);
    res.rows.forEach((element: any) => {
      element.orderDate = element.orderDate ? dayjs(element.orderDate).format('YYYY-MM-DD') : '暂无';
      element.deliveryDate = element.deliveryDate ? dayjs(element.deliveryDate).format('YYYY-MM-DD') : '暂无';
      element.changeDate = element.changeDate ? dayjs(element.changeDate).format('YYYY-MM-DD') : '暂无';
      element.shippingDate = element.shippingDate ? dayjs(element.shippingDate).format('YYYY-MM-DD') : '暂无';
      element.storageTime = element.storageTime ? dayjs(element.storageTime).format('YYYY-MM-DD') : '暂无';
    });
    total.value = res.total;
    tableData.value = res.rows as TableRow[];
  } catch (error) {
    console.error('搜索失败:', error);
    ElMessage.error('搜索失败');
  } finally {
    setTimeout(() => {
      loadingSearch.value = false;
      loadingTable.value = false;
    });
  }
};

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key as keyof SearchForm] = '' as any;
  });
  pageNum.value = 1;
  handleSearch();
};

const handleAdd = () => {
  formComponent.value?.showDialog({});
};

const handleEdit = (row: TableRow) => {
  formComponent.value?.showDialog({ id: row.id });
};

const handleView = (row: TableRow) => {
  detailComponent.value?.showDialog({ id: row.id });
};

const handleImport = () => {
  importComponent.value?.showDialog();
};

const handleExport = () => {
  // 导出功能实现
  ElMessage.info('导出功能待实现');
};

// 更新删除方法
const handleDelete = async (id: number | string) => {
  try {
    await deleteBydSpecialPojectDataById([id]);
    ElMessage.success('删除成功');
    handleSearch();
    deleteVisible.value[id] = false;
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val: number) => {
  pageNum.value = val;
  handleSearch();
};

// 生命周期
onMounted(() => {
  handleSearch();
});
</script>

<style lang="scss" scoped>
/* 样式 */
::v-deep .el-form-item {
  margin-bottom: 5px !important;
}

::v-deep .el-form {
  padding: 10px;
}

.btmOption {
  padding: 5px 15px;
  display: flex;
  justify-content: space-between;
}

::v-deep .el-table__body-wrapper {
  min-height: 550px;
}


.pagination {
  position: absolute;
  bottom: 0px;
  width: 100%;
  background: #fff;
}

.option-class {
  display: flex;
  justify-content: space-around;
}
</style>
